//
//  HXHomeViewController.m
//  Number To English
//
//  Created by 朱志雄 on 2024/7/23.
//
#define STATE_BAR_HEIGHT [UIApplication sharedApplication].statusBarFrame.size.height
#define FIT_WIDTH   [UIScreen mainScreen].bounds.size.width/375
#define FIT_HEIGHT  [UIScreen mainScreen].bounds.size.height/667
#define KScreen_W  [UIScreen mainScreen].bounds.size.width
#define KScreen_H  [UIScreen mainScreen].bounds.size.height

#define RGBACOLOR(r,g,b,a) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:(a)]
#define ZXMainColor RGBACOLOR(209, 58, 42, 1)
#import "HXHomeViewController.h"
#import "FSTextView.h"
@interface HXHomeViewController ()<UITextViewDelegate>

@property(nonatomic,weak)     FSTextView *numText;
@property(nonatomic,weak)   UILabel *resL;

@end

@implementation HXHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    
    self.view.backgroundColor = RGBACOLOR(225, 245, 255, 1);
    UIImageView *backView = [[UIImageView alloc] initWithFrame:self.view.bounds];
    backView.contentMode = UIViewContentModeScaleAspectFill;
    backView.image = [UIImage imageNamed:@"backimage"];
    [self.view addSubview:backView];
    
    [self loadNavView];
    [self loadBody];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = YES;
}

-(void)loadNavView{
    UIView *navView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreen_W, STATE_BAR_HEIGHT + 44)];
    navView.backgroundColor = RGBACOLOR(235, 230, 235, 1);
    [self.view addSubview:navView];
    
    
    UILabel *titleL = [[UILabel alloc] initWithFrame:CGRectMake(100, STATE_BAR_HEIGHT + 8, KScreen_W - 200, 25)];
    titleL.text = @"Number To English";
    titleL.font = [UIFont boldSystemFontOfSize:20];
    titleL.numberOfLines = 0;
    titleL.textAlignment = NSTextAlignmentCenter;
    titleL.textColor = RGBACOLOR(22, 22, 22, 1);
    [navView addSubview:titleL];
}


-(void)loadBody{
    UILabel *titleL = [[UILabel alloc] initWithFrame:CGRectMake(16, STATE_BAR_HEIGHT + 64, 200, 30)];
    titleL.text = @"Enter numbers";
    titleL.font = [UIFont fontWithName:@"PingFangSC-Regular" size:20];
    titleL.textColor = [UIColor whiteColor];
    [self.view addSubview:titleL];
    
    
    UIView *shuruView = [[UIView alloc] initWithFrame:CGRectMake(16, CGRectGetMaxY(titleL.frame) + 6 , KScreen_W - 32, 116)];
    shuruView.backgroundColor = RGBACOLOR(255, 250, 255, 1);
    shuruView.layer.borderColor = RGBACOLOR(245, 250, 240, 1).CGColor;
    shuruView.layer.borderWidth = 1.0f;
    shuruView.layer.cornerRadius = 5;
    shuruView.layer.masksToBounds = YES;
    [self.view addSubview:shuruView];
    
    
    FSTextView *numText = [[FSTextView alloc] initWithFrame:CGRectMake(16, 10 , shuruView.bounds.size.width - 32, 88)];
    numText.placeholder = @"";
    self.numText = numText;
    numText.delegate = self;
    numText.keyboardType = UIKeyboardTypeNumberPad;
    [numText becomeFirstResponder];
    numText.font = [UIFont fontWithName:@"PingFangSC-Regular" size:20];
    numText.textColor = [UIColor blackColor];
    [shuruView addSubview:numText];
    
    
    UILabel *titleLs = [[UILabel alloc] initWithFrame:CGRectMake(16, CGRectGetMaxY(shuruView.frame) + 30, 200, 30)];
    titleLs.text = @"English";
    titleLs.font = [UIFont fontWithName:@"PingFangSC-Regular" size:20];
    titleLs.textColor = [UIColor whiteColor];
    [self.view addSubview:titleLs];
    
    
    UIView *resView = [[UIView alloc] initWithFrame:CGRectMake(16, CGRectGetMaxY(titleLs.frame) + 6 , KScreen_W - 32, 116)];
    resView.backgroundColor = RGBACOLOR(255, 250, 255, 1);
    resView.layer.borderColor = RGBACOLOR(245, 250, 240, 1).CGColor;
    resView.layer.borderWidth = 1.0f;
    resView.layer.cornerRadius = 5;
    resView.layer.masksToBounds = YES;
    [self.view addSubview:resView];
    
    
    UILabel *resL = [[UILabel alloc] initWithFrame:CGRectMake(16, 4 , shuruView.bounds.size.width - 32, 68)];
    self.resL = resL;
    resL.numberOfLines = 0;
    resL.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16];
    resL.textColor = [UIColor blackColor];
    [resView addSubview:resL];
    
    
    UIButton *copyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [copyBtn addTarget:self action:@selector(CopyClick) forControlEvents:UIControlEventTouchUpInside];
    copyBtn.frame = CGRectMake(resView.bounds.size.width - 54,resView.bounds.size.height - 50,50, 50);
    [copyBtn setImage:[UIImage imageNamed:@"复制"] forState:UIControlStateNormal];
    [resView addSubview:copyBtn];
    
}


-(void)CopyClick{
    if (self.numText.text.length == 0) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Please enter number" message:nil preferredStyle:UIAlertControllerStyleAlert];

        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"Done" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            // 用户点击确定按钮后的操作
        }];

        [alert addAction:okAction];
        // 在视图控制器中显示弹框
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Copy successful" message:nil preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"Done" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        // 用户点击确定按钮后的操作
    }];

    [alert addAction:okAction];
    // 在视图控制器中显示弹框
    [self presentViewController:alert animated:YES completion:nil];
    
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = self.resL.text;
}


- (void)textViewDidChange:(UITextView *)textView {
    NSInteger maxLength = 8; // 设置最大字数
    NSInteger currentLength = textView.text.length;
    if (currentLength > maxLength) {
        // 如果超过最大字数，截取字符串
        textView.text = [textView.text substringToIndex:maxLength];
        NSLog(@"输入字数超出限制！");
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"The number entered exceeds the limit" message:nil preferredStyle:UIAlertControllerStyleAlert];

        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"Done" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            // 用户点击确定按钮后的操作
        }];

        [alert addAction:okAction];
        // 在视图控制器中显示弹框
        [self presentViewController:alert animated:YES completion:nil];
    }
    

    int num = [textView.text intValue];
    self.resL.text = [NSString stringWithFormat:@"%@",numberToWords(num)];
  
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}


NSString *numberToWordsHelper(int num, BOOL isLastGroup) {
    if (num == 0) {
        return @"";
    }
    
    // 定义数字和英文单词的映射（只到十九）
    NSArray<NSString *> *units = @[@"", @"One", @"Two", @"Three", @"Four", @"Five", @"Six", @"Seven", @"Eight", @"Nine", @"Ten", @"Eleven", @"Twelve", @"Thirteen", @"Fourteen", @"Fifteen", @"Sixteen", @"Seventeen", @"Eighteen", @"Nineteen"];
    // 定义十的倍数（二十到九十）
    NSArray<NSString *> *tens = @[@"", @"", @"Twenty", @"Thirty", @"Forty", @"Fifty", @"Sixty", @"Seventy", @"Eighty", @"Ninety"];
    
    if (num < 20) {
        return units[num];
    } else if (num < 100) {
        int ten = num / 10;
        int one = num % 10;
        if (one == 0) {
            return tens[ten];
        } else {
            return [NSString stringWithFormat:@"%@-%@", tens[ten], units[one]];
        }
    }
    
    // 处理百位及以上的情况
    int hundred = num / 100;
    int rest = num % 100;
    NSString *result = [NSString stringWithFormat:@"%@ Hundred", units[hundred]];
    if (rest > 0) {
        result = [result stringByAppendingString:@" "];
        result = [result stringByAppendingString:numberToWordsHelper(rest, NO)];
    }
    return result;
}

NSString *numberToWords(int num) {
    if (num == 0) {
        return @" ";
    }
    
    // 定义大单位
    NSArray<NSString *> *bigUnits = @[@"", @"Thousand", @"Million"];
    
    NSString *result = @"";
    int groupIndex = 0;
    while (num > 0) {
        int group = num % 1000;
        if (group > 0) {
            NSString *groupWords = numberToWordsHelper(group, groupIndex == 2); // 最后一组（百万位）不加"And"
            if (![result isEqualToString:@""]) {
                if (![result hasSuffix:@"And"]) {
                    // 不是以"And"结尾，则需要添加大单位
                    result = [NSString stringWithFormat:@"%@ %@ %@", result, bigUnits[groupIndex], groupWords];
                } else {
                    // 以"And"结尾，则直接添加组单词
                    result = [result stringByAppendingString:[NSString stringWithFormat:@" %@", groupWords]];
                }
            } else {
                // 结果字符串为空，直接添加组单词
                result = groupWords;
            }
        }
        num /= 1000;
        groupIndex++;
    }

    return result;
}


@end
